package com.ironmaking.Handler.Security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ironmaking.Utils.token.JWTutil;
import com.ironmaking.Vo.results.ActionResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName AuthorizationHandler
 * @Description 权限验证用，未登录（携带token）无法访问api
 */

@Component
public class AuthorizationHandler implements HandlerInterceptor {

    @Autowired
    JWTutil jwTutil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * handler保存了本次请求的controller也就是接口方法的一些信息，如类，方法，参数等
         * 如果是一次静态资源的请求则该handler不应该是HandlerMethod的实现类
         * 判断是否是一个正常的接口，如果是则进行鉴权操作，不是则直接放行
         */
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;// 把handler强转为HandlerMethod
            Security security = handlerMethod.getMethod().getAnnotation(Security.class);
            if (security != null) {
                // 对用户进行鉴权
                String token = request.getHeader("Authorization");
                if(token == null || jwTutil.checkToken(token) == null) {
                    ObjectMapper mapper = new ObjectMapper();
                    response.setContentType("application/json;charset=utf-8");
                    response.getWriter().print(mapper.writeValueAsString(ActionResult.fail(401,"用户未登录，请登录后操作！")));
                    return false;
                }
                else return true;
            }
        }
        return true;
    }
}
